<template>
  <div class="ant-pro-multi-tab">
    <div class="ant-pro-multi-tab-wrapper">
      <a-tabs
        v-model="activeKey"
        :hide-add="true"
        type="editable-card"
        :tab-bar-style="{ background: '#FFF', margin: 0, paddingLeft: '16px', paddingTop: '1px' }"
        @tabClick="tabClick"
        @edit="close"
      >
        <a-tab-pane
          v-for="(item, index) of tabs"
          :key="index"
          :closable="tabs.length > 1 && item.path !== '/index'"
        >
          <template slot="tab">
            <span v-if="item.fullPath === '/index'">{{ item.title }}</span>
            <a-dropdown
              v-else
              :trigger="['contextmenu']"
            >
              <span>{{ item.title }}</span>
              <a-menu
                slot="overlay"
                @click="(e) => closeMenuClick(e.key, index)"
              >
                <a-menu-item key="closeThat"> 关闭当前标签 </a-menu-item>
                <a-menu-item key="closeRight"> 关闭右侧 </a-menu-item>
                <a-menu-item key="closeLeft"> 关闭左侧 </a-menu-item>
                <a-menu-item key="closeAll"> 关闭其它 </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<script>
/*
* 忽略noTab
* <a-button
                    @click="$router.push({
                        path:'/construction-node/details?id=673335186968158208&isdelay=3&reviewButton=0',
                        query:{
                            ignoreNoTab:1,
                            history:JSON.stringify([
                               {
                                   title:'施工进度总计划列表',
                                   path:'/construction/progress',
                               },
                               {
                                   title:'施工进度总计划管理',
                                   path:'/construction/manager?planId=673334859900526593',
                               },
                               {
                                   title:'节点详情',
                                   path:'/construction-node/details?id=673335186968158208&isdelay=3&reviewButton=0',
                               }
                            ])
                        }
                    })">
                    关闭
                </a-button>
*
*
* */
import { mapState } from 'vuex'
import { BUSINESS_MENU_TYPE } from '@/config/businessConfig'

export default {
  name: 'Index',
  data() {
    return {
      activeKey: 0,
      tabs: [
        {
          title: ' 首页',
          fullPath: '/index',
          path: '/index',
          history: []
        }
      ]
    }
  },
  computed: {
    ...mapState({
      activeCodes: (state) => state.user.activeCodes,
      businessSearchConditions: (state) => state.user.businessSearchConditions
    })
  },
  created() {
    this.init()
  },
  watch: {
    //监听路由变更
    $route(newVal, oldVal) {
      // this.init()
      let { meta, fullPath, matched, query } = newVal
      if(query.nameTil) {
        meta.title = query.nameTil
      }
      // console.log('当前：', newVal)
      // console.log(this.tabs)
      // console.log('this.tabs',this.$store.getters['tabInfo/GET_PATHMAP'])
      // console.log('原来：', oldVal)
      let newValComponentName = newVal.matched[newVal.matched.length - 1].components.default?.name || newVal.matched[newVal.matched.length - 1].name
      let oldValComponentName = oldVal.matched[newVal.matched.length - 1]?.components.default?.name || newVal.matched[newVal.matched.length - 1].name
      if(!newVal.meta.noTab) {
        this.$store.commit('tabInfo/ADD_CACHE_PAGE', newValComponentName)
      }
      // this.$console(this.$store.state.tabInfo.cachePages)

      if (fullPath === '/index') return

      //检查当前tab里面有这条数据
      let resIndex = this.tabs.findIndex((item) => {
        if (!!item.codes && !!item.codes[0]) {
          return item.path === newVal.path && item.codes[item.codes.length - 1] === this.activeCodes[this.activeCodes.length - 1]
        } else {
          return item.path === newVal.path
        }
      })
      // 区分业务执行，业务管控，业务查询下的路由
      const businessCodes = Object.keys(BUSINESS_MENU_TYPE).map((key) => BUSINESS_MENU_TYPE[key].code)
      const currentBusiness = Object.keys(BUSINESS_MENU_TYPE)
        .map((key) => BUSINESS_MENU_TYPE[key])
        .find((item) => this.activeCodes.some((code) => item.code === code))
      if (resIndex !== -1 && businessCodes.some((code) => code === newVal.query?.query)) {
        const sameTab = this.tabs.find((item) => item.path === newVal.path && item.query?.query === newVal.query?.query)
        resIndex = sameTab ? resIndex : -1
      }
      //已有tab，可能是详情页面返回，也可能是tab页跳tab页
      if (resIndex !== -1) {
        // console.log(this.tabs[resIndex].history)
        // console.log(this.tabs[resIndex].history.length)
        //如果this.tabs[resIndex].history.length > 4，那么说明是tab页跳tab页，然后要把history里面的从第4条开始的记录，全部给删除缓存
        if (!!this.tabs[resIndex].history && this.tabs[resIndex].history?.length > 4) {
          for (let i = 4; i < this.tabs[resIndex].history.length; i++) {
            let item = this.tabs[resIndex].history[i]
            // this.$store.commit('tabInfo/DEL_CACHE_PAGE', item.componentName)
          }
          // this.$console(this.$store.state.tabInfo.cachePages)
        }
        if (!!this.tabs[this.activeKey].history && this.tabs[this.activeKey].history.length > matched.concat().length) {
          // console.log('已有tab，可能是详情页面返回，也可能是tab页跳tab页，发射事件:fullPath', newVal.path)
          this.$bus.$emit('handleRefresh' + newVal.path)
        }

        this.activeKey = resIndex
        this.tabs[this.activeKey].fullPath = fullPath
        // console.log('前面', this.tabs[this.activeKey].history.length)

        this.tabs[this.activeKey].history = matched.concat().map(function (route, index) {
          return {
            disabled: index < 2, // 禁止前两级跳转
            title: route.meta.title,
            path: route.path,
            fullPath: route.path,
            componentName: route.components.default?.name || route.name
          }
        })

        // console.log('后面', this.tabs[this.activeKey].history.length)
      } else {
        let urlOb = this.$parseURL(fullPath)
        // console.log(urlOb)
        //没有新的tab页面，并且没有配置ignoreNoTab
        if (meta.noTab && !urlOb.params.ignoreNoTab) {
          // if (meta.noTab) {
          this.tabs[this.activeKey].fullPath = fullPath
          let resIndex1 = this.tabs[this.activeKey].history.findIndex((v) => v.fullPath === newVal.fullPath)
          // console.log('找到了吗？2', resIndex1)

          //在当前tab页的history数组里面，添加一条记录
          if (resIndex1 === -1) {
            this.tabs[this.activeKey].history.push({
              disabled: false,
              title: meta.title,
              fullPath: newVal.fullPath,
              path: newVal.fullPath,
              componentName: newValComponentName
            })
            // //需要缓存的url，其实全局的都做了，只是单独要上安监的
            // let keepAliveUrls = ['quality/safe', 'safety', 'safetySupervision']
            //
            // let isSafe = keepAliveUrls.find(v => oldVal.path.search(v) !== -1)
            // console.log('是否是安监', isSafe)
            // if (!isSafe) {
            //   //删除上一个页面的缓存
            // this.$store.commit('tabInfo/DEL_CACHE_PAGE', oldValComponentName)
            // }
          } else {
            //删除tab页的history数组里面，当前记录往后的数据,应该是多级详情页面返回上一级
            const delPages = this.tabs[this.activeKey].history.splice(resIndex1 + 1, this.tabs[this.activeKey].history.length - 1 - resIndex1)
            // 清除已删除的页面的缓存
            delPages.forEach((item) => {
              this.$store.commit('tabInfo/DEL_CACHE_PAGE', item.componentName)
            })
          }
        } else {
          //新开一个tab页,分下面两种情况
          //如果配置了ignoreNoTab，就要重新单独开一个tab
          if (urlOb.params.ignoreNoTab) {
            let noTabHistory = JSON.parse(decodeURIComponent(urlOb.params.history))
            noTabHistory.map((v) => {
              v.disabled = false
              v.fullPath = v.path
            })

            let routeHistory = matched.concat().map(function (route, index) {
              return {
                disabled: index < 2, // 禁止前两级跳转
                title: route.meta.title,
                path: route.path,
                fullPath: route.path,
                componentName: route.components.default?.name || route.name
              }
            })
            routeHistory.pop()

            let history = [...routeHistory, ...noTabHistory]
            // console.log(history)

            let isOpenIndex = this.tabs.findIndex((v) => v.path === noTabHistory[0].path)
            if (isOpenIndex === -1) {
              this.addTab({
                title: currentBusiness ? `${noTabHistory[0].title}(${currentBusiness.name.slice(2)})` : noTabHistory[0].title,
                fullPath: newVal.fullPath,
                path: noTabHistory[0].path,
                history: history,
                query: newVal.query,
                codes: this.activeCodes
              })
            } else {
              this.activeKey = isOpenIndex
              //返回列表了，fullpath就会等于path，就会少一级history，然后点关闭的时候就会跳转到默认模块
              if (this.tabs[this.activeKey].fullPath === this.tabs[this.activeKey].path) {
                this.tabs[this.activeKey].history = history
              }
              this.tabs[this.activeKey].fullPath = newVal.fullPath
              this.setStore()
            }
          } else {
            //没有tab，也不是noTab，那就是新开一个tab页
            this.addTab({
              title: currentBusiness ? `${meta.title}(${currentBusiness.name.slice(2)})` : meta.title,
              fullPath: newVal.fullPath,
              path: newVal.path,
              query: newVal.query,
              codes: this.activeCodes,
              history: matched.concat().map(function (route, index) {
                return {
                  disabled: index < 2, // 禁止前两级跳转
                  title: route.meta.title,
                  path: route.path,
                  fullPath: route.path,
                  componentName: route.components.default?.name || route.name
                }
              })
            })
          }
        }
      }
      this.setStore()
    },
    businessSearchConditions: {
      handler() {
        this.tabs = [
          {
            title: ' 首页',
            fullPath: '/index',
            path: '/index',
            history: []
          }
        ]
        this.activeKey = 0
        this.setStore()
        this.$store.commit('SET_ACTIVE_CODES', [])
        this.$router.push(this.tabs[this.activeKey].fullPath)
      },
      deep: true
    }
  },
  mounted() {
    this.$bus.$on('close', () => {
      console.log('close')
      this.back()
      // this.close(this.activeKey + 1)
    })
    // 新增关闭页面方法()
    this.$bus.$on('closePage', (e) => {
      // 是否需要关闭标签页
      if (e) {
        this.back()
        this.$nextTick(()=>{this.close(this.activeKey)})
      }else{
        this.back()
      }
      
    })
    this.$bus.$on('closeIframe', (path) => {
      this.close(this.tabs.findIndex((i) => i.path === path))
    })
    window.onunload = () => {
      this.$storageSet(
        'tabs',
        this.tabs.filter((item) => item.path !== '/index')
      )
      this.$storageSet('tabs-activeKey', this.activeKey)
    }
  },
  destroyed() {
    this.$bus.$off('close')
    this.$bus.$off('closePage')
    this.$bus.$off('closeIframe')
  },
  methods: {
    async backParent(notice) {
      // console.log(notice)
    },
    /**
     * 关闭标签页时，需要清除页码信息的缓存
     * @param {Array} list 关闭的标签页数组
     */
    clearPaginationCache(list = []) {
      const cachePagination = sessionStorage.getItem('cachePagination')
      const cachePaginationObj = cachePagination ? JSON.parse(cachePagination) : {}
      list.forEach((item) => {
        delete cachePaginationObj[item.fullPath]
      })
      sessionStorage.setItem('cachePagination', JSON.stringify(cachePaginationObj))
    },
    //初始化，从Storage里面读取存的数据，并复原
    init() {
      this.tabs = [
        {
          title: ' 首页',
          fullPath: '/index',
          path: '/index',
          history: []
        },
        ...this.$storageGet('tabs', [])
      ]
      this.activeKey = this.$storageGet('tabs-activeKey', this.tabs.length - 1)
      this.setStore()
      this.$router.push(this.tabs[this.activeKey].fullPath)
    },
    setStore() {
      this.$store.commit('tabInfo/SET_PATHMAP', this.tabs)
      this.$store.commit('tabInfo/SET_ACTIVE_KEY', this.activeKey)
    },
    addTab(row) {
      this.tabs.push(row)
      this.activeKey = this.tabs.length - 1
      this.setStore()
    },
    tabClick(index) {
      this.activeKey = index
      this.setStore()
      this.$store.commit('SET_ACTIVE_CODES', this.tabs[index].codes || this.activeCodes)
      let tab = this.tabs[index]
      this.$router.push(tab.fullPath ?? tab.path)
    },
    //返回当前tab的上一条历史记录
    async back() {
      
      console.log('close')
      if (!(await this.checkCanBackOrClose(this.activeKey))) return
      // console.log('back')
      let currentTab = this.tabs[this.activeKey]
      console.log('back里面的handleRefresh，fullPath', currentTab.path)

      this.$bus.$emit('handleRefresh' + currentTab.path)
      if (currentTab.path === '/index') {
        return window.history.back()
      }
      if (!currentTab.history) {
        return window.history.back()
      }
      let history = currentTab.history
      this.$store.commit('tabInfo/DEL_CACHE_PAGE', history[history.length - 1].componentName)
      this.$router.push(history[history.length - 2].fullPath)
      currentTab.fullPath = history[history.length - 2].fullPath
      history.pop()
      this.setStore()
    },
    //关闭当前tab
    async close(index) {
      this.removeItemSessionStorage()
      if (!(await this.checkCanBackOrClose(index))) return
      this.$store.commit('tabInfo/DEL_CACHE_PAGES', this.tabs[index])
      if (this.tabs.length === 2) {
        this.activeKey = 0
        // SET_ACTIVE_CODES需在路由跳转之前
        this.$store.commit('SET_ACTIVE_CODES', this.tabs[this.activeKey]?.codes || [])
        this.$router.push('/index')
      } else {
        if (index === this.activeKey) {
          if (index === 0) {
            this.activeKey = index + 1
          } else {
            this.activeKey = index - 1
          }
          this.$store.commit('SET_ACTIVE_CODES', this.tabs[this.activeKey]?.codes || [])
          this.$router.push(this.tabs[this.activeKey].fullPath)
        } else {
          if (index < this.activeKey) {
            this.activeKey--
            this.$store.commit('SET_ACTIVE_CODES', this.tabs[this.activeKey]?.codes || [])
          }
        }
      }
      this.clearPaginationCache(this.tabs.splice(index, 1))
      this.setStore()
    },
    removeItemSessionStorage() {
      let complaints = sessionStorage.getItem('complaints') ?? null
      complaints && sessionStorage.removeItem('complaints')
      let maintenance = sessionStorage.getItem('maintenance') ?? null
      maintenance && sessionStorage.removeItem('maintenance')
    },
    //菜单
    closeMenuClick(key, index) {
      switch (key) {
        case 'closeThat':
          this.close(index)
          break
        case 'closeRight':
          for (let i = index + 1; i < this.tabs.length; i++) {
            this.$store.commit('tabInfo/DEL_CACHE_PAGES', this.tabs[i])
          }
          this.clearPaginationCache(this.tabs.splice(index + 1, this.tabs.length - index))
          this.activeKey = index
          this.$store.commit('SET_ACTIVE_CODES', this.tabs[this.activeKey]?.codes || [])
          this.$router.push(this.tabs[this.activeKey].fullPath)
          break
        case 'closeLeft':
          for (let i = 1; i < index; i++) {
            this.$store.commit('tabInfo/DEL_CACHE_PAGES', this.tabs[i])
          }
          this.clearPaginationCache(this.tabs.splice(1, index - 1))
          if (this.activeKey === index) {
            this.activeKey = 1
          } else {
            if (this.activeKey > index) {
              this.activeKey = index
            } else {
              this.activeKey = 1
              this.$store.commit('SET_ACTIVE_CODES', this.tabs[this.activeKey]?.codes || [])
              this.$router.push(this.tabs[this.activeKey].fullPath)
            }
          }
          break
        case 'closeAll':
          for (let i = 1; i < index; i++) {
            this.$store.commit('tabInfo/DEL_CACHE_PAGES', this.tabs[i])
          }
          for (let i = index + 1; i < this.tabs.length; i++) {
            this.$store.commit('tabInfo/DEL_CACHE_PAGES', this.tabs[i])
          }
          this.clearPaginationCache(this.tabs.splice(1, index - 1))
          this.clearPaginationCache(this.tabs.splice(2, this.tabs.length - 1))
          this.activeKey = 1
          this.$store.commit('SET_ACTIVE_CODES', this.tabs[this.activeKey]?.codes || [])
          this.$router.push(this.tabs[this.activeKey].fullPath)
          break
      }
      this.setStore()
    },
    async checkCanBackOrClose(index) {
      //todo 这里实现不好，后面要改应该，目前只是关闭当前页面会判断是否有回调
      if (index === this.activeKey) {
        let tab = this.tabs[index]
        if (this.$multiTab.callbackFnMap[tab.fullPath]) {
          await this.$multiTab.callbackFnMap[tab.fullPath]()
          this.$multiTab.deleteCallback(tab.fullPath)
          return false
        }
      }
      return true
    }
  }
}
</script>

<style scoped lang="less">
@import '../index';

@deep: ~'>>>';
@multi-tab-prefix-cls: ~'@{ant-pro-prefix}-multi-tab';
@multi-tab-wrapper-prefix-cls: ~'@{ant-pro-prefix}-multi-tab-wrapper';

.@{multi-tab-prefix-cls} {
  //margin: -23px -24px 24px -24px;
  background: #fff;
}

.topmenu .@{multi-tab-wrapper-prefix-cls} {
  margin: 0;
}

.ant-pro-grid-content.wide {
  margin: 0;
  max-width: 100%;
}

.topmenu.content-width-Fluid .@{multi-tab-wrapper-prefix-cls} {
  // max-width: 100%;
  margin: 0 auto;
}

// @{deep} .ant-tabs-close-x {
//   color: rgb(171, 171, 171) !important;
//   position: absolute;
//   top: 6px;
//   right: 6px;
// }
</style>
